package com.pluszg.nutrition.database.aop;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.pluszg.nutrition.common.exception.PlusBusinessException;
import com.pluszg.nutrition.common.req.PageBean;
import com.pluszg.nutrition.common.resp.PageResponse;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

import java.util.Arrays;
import java.util.List;

/**
 * aop环绕通知，在getPage*()方法前后执行，与mybatis的PageHelper插件一起完成分页
 */
@Aspect
public class PageBeanAspect {

    @Around(value = "execution(* com.pluszg.nutrition.database.mapper..getPage*(..))")
    public Object invoke(ProceedingJoinPoint joinPoint) throws Throwable {

        // 取出PageBean
        Object[] args = joinPoint.getArgs();

        PageBean pageBean = (PageBean) Arrays.stream(args)
                .filter(obj -> obj instanceof PageBean)
                .findFirst().orElse(null);

        // 如果分页，指定分页参数
        if (pageBean != null && pageBean.isPaginate()) {
            if (pageBean.getPageNumber() <= 0 || pageBean.getPageSize() <= 0) {
                throw new PlusBusinessException("分页参数不合法");
            }
            PageHelper.startPage(pageBean.getPageNumber(), pageBean.getPageSize());
        }

        Object returnValue = joinPoint.proceed(args);
        // 如果分页，获得总记录数
        if (pageBean != null && null != returnValue) {
            PageResponse response = (PageResponse) Arrays.stream(args)
                    .filter(obj -> obj instanceof PageResponse)
                    .findFirst().orElseGet(PageResponse::new);
            response.setPageNumber(pageBean.getPageNumber());
            response.setPageSize(pageBean.getPageSize());
            if (pageBean.isPaginate() && returnValue instanceof Page) {
                Page page = (Page) returnValue;

                response.setTotalRecord(page.getTotal());
                response.setTotalPage(page.getPages());
                response.setResultList(page.getResult());
            } else if (!pageBean.isPaginate() && returnValue instanceof List) {
                List<?> list = (List) returnValue;

                response.setTotalRecord(list.size());
                response.setTotalPage(1);
                response.setResultList(list);
            }
        }
        return returnValue;
    }

}